//
//  HEDoctorInfoDetailsViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/11/17.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEDoctorInfoDetailsViewController.h"
#import "HEDoctorHeadCell.h"
#import "HEDoctorSignCell.h"
#import "HEDoctorServerCell.h"
#import "HEDoctorServerInfoCell.h"
#import "HEDoctorCommentHeadCell.h"
#import "HEDoctorCommentCell.h"
#import "HEDoctorInfoModel.h"
#import "HEDoctorServerResponse.h"
#import "HEDoctorCommentModel.h"
#import "HEDoctorServerNoticeCell.h"
#import "HEDoctorCommentListViewController.h"
#import "HERealNameAuthAlterView.h"
#import "HERealNameAuthAlterController.h"
#import "HEDoctorMainPageViewController.h"
#import "HEDoctorServerComfireViewController.h"
#import "HEAddHealthReportViewController.h"
#import "HEDoctorPrivateSignViewController.h"
#import "HETWViewController.h"
#import "HEApplyPlusViewController.h"

@interface HEDoctorInfoDetailsViewController ()<UITableViewDelegate, UITableViewDataSource, HEDoctorServerCellDelegate, HEDoctorHeadCellDelegate, HEDoctorSignCellDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) HEDoctorServerResponse *details;
@property (nonatomic, strong) NSMutableArray <HEDoctorCommentModel *> *commentList;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

@property (nonatomic, strong) NSMutableArray <HEDoctorInfoModel *> *showList;
@property (nonatomic, strong) NSMutableArray <HEDoctorInfoModel *> *privateDoctors;
@property (nonatomic, assign) BOOL isShowServerDetailCell;
//@property (nonatomic, assign) BOOL isHasPrivate; // 判断用户是否已经签约过

@property (nonatomic, strong) UIButton *bottomView;

@end

@implementation HEDoctorInfoDetailsViewController


- (NSMutableArray<HEDoctorCommentModel *> *)commentList {
    if (!_commentList) {
        _commentList = [NSMutableArray array];
    }
    return _commentList;
}

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImageView *warp = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, ZXNavBarHeight)];
    warp.image = IMAGE_NAMED(@"doctor_bk");
    warp.contentMode = UIViewContentModeScaleAspectFill;
    warp.clipsToBounds = YES;
    [self.zx_navBar  addSubview:warp];
    [self.zx_navBar sendSubviewToBack:warp];
    self.zx_navLineView.hidden = YES;
    
    [self initUI];
    [self initTabBarView];
    
    [self loadData];
}

- (void)initTabBarView {
    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = CNavBgColor;
    _bottomView.titleLabel.font = DYBlodFont(18);
    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    
    if (_type == HEDoctorInfoDetailsPageTypeByPrivateDoctor) {
        [bottomView setTitle:@"签约" forState:UIControlStateNormal];
    }else {
        [bottomView setTitle:@"提交" forState:UIControlStateNormal];
    }
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.equalTo(self.view).offset(-ZXSafeAreaBottom);
    }];
}

- (void)submit {
    
    if (self.formModel.doc_selectServer == nil) {
        if (_type == HEDoctorInfoDetailsPageTypeByPrivateDoctor) {
            [Dialog toastBottom:@"请选择签约时长"];
        }else {
            [Dialog toastBottom:@"请选择您要咨询的服务"];
        }
        return;
    }

    
    if (![[UserManager sharedUserManager] getUserInfo].verifyStatus) {
            HERealNameAuthAlterController *vc = [HERealNameAuthAlterController new];
            [self.view addSubview:vc.view];
        return;
    }
    
    if (self.formModel.doc_selectServer.channel == HEChannelTypeHealthGuide) {
        HEAddHealthReportViewController *vc = [HEAddHealthReportViewController new];
        vc.userModel = _details.info;
        vc.selectServerModel = self.formModel.doc_selectServer;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (self.formModel.doc_selectServer.channel == HEChannelTypePrivateDoctors) {
        HEDoctorPrivateSignViewController *vc = [HEDoctorPrivateSignViewController new];
        vc.userModel = _details.info;
        vc.selectServerModel = self.formModel.doc_selectServer;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (self.formModel.doc_selectServer.channel == HEChannelTypePTConsultation) {
        HETWViewController *vc = [HETWViewController new];
        vc.userModel = _details.info;
        vc.selectServerModel = self.formModel.doc_selectServer;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        HEDoctorServerComfireViewController *vc = [HEDoctorServerComfireViewController new];
        HEServerComfireModel *comfireModel = [HEServerComfireModel new];
        comfireModel.icon_url = _details.info.avatar;
        comfireModel.topStr = _details.info.realname;
        comfireModel.middleStr = _details.info.KDeptStr;
        comfireModel.bottomStr = _details.info.hospital_name;
        comfireModel.payParams = @[self.formModel.doc_selectServer.server_name,
                                   [NSString stringWithFormat:@"￥%@%@", [NSDecimalNumber rounding:self.formModel.doc_selectServer.price afterPoint:2], self.formModel.doc_selectServer.unit]];
        
        HECreateOrderRequest *request = [HECreateOrderRequest new];
        request.orderType = HEOrderTypeGeneral;
        request.doctor_id = _details.info.user_id;
        request.total = 1;
        request.goodsId = self.formModel.doc_selectServer.goods_id;
        request.channel = self.formModel.doc_selectServer.channel;
        request.skuId = self.formModel.doc_selectServer.attr_id;
        request.source = HEOrderSourceTypeiOS;
        request.type = HESubmitPreviewTypeByGoodsDetails;
        request.appSource = KAppSource;
    
        HEExtraDoctorInfoModel *extra = [HEExtraDoctorInfoModel new];
        extra.planId = 0;
        extra.order_type = self.formModel.doc_selectServer.channel;
    
        extra.doctor_info = [DoctorInfo new];
        extra.doctor_info.user_id = _details.info.user_id;
        extra.doctor_info.post_name = _details.info.post_name;
        extra.doctor_info.avatar = _details.info.avatar;
        extra.doctor_info.depart_name = _details.info.depart_name;
        extra.doctor_info.realname = _details.info.realname;
        request.extras = [extra mj_JSONString];
        
        vc.comfireModel = comfireModel;
        vc.orderRequest = request;
        vc.price = self.formModel.doc_selectServer.price;
        [self.navigationController pushViewController:vc animated:YES];
    }

    
    //

}

- (void)initUI {
    CGFloat tabbarHeight = 49 + KSafeTabbarHeight;
    _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight- ZXNavBarHeight - tabbarHeight) style:UITableViewStylePlain];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollsToTop = YES;
    _tableView.tableFooterView = [[UIView alloc] init];
    
    self.tableView.backgroundColor = CViewBgColor;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
}

- (void)initCell {
    // 总段
    _sections = [NSMutableArray array];
    NSMutableArray *classArr = [NSMutableArray array];
    
    self.formModel.doc_pageType = _type;
    
    self.formModel.doc_details = self.details.info;
    if (_type == HEDoctorInfoDetailsPageTypeByPrivateDoctor) {
        self.formModel.doc_serverList = _privateDoctors;
    }else {
        self.formModel.doc_serverList = _showList;
    }
    self.formModel.doc_commentList = self.commentList;
 
    // 头部
    GDFiterCellModel *headModel = [GDFiterCellModel new];
    headModel.cellKlass = HEDoctorHeadCell.class;
    
    // 签约
    GDFiterCellModel *siginModel = [GDFiterCellModel new];
    siginModel.cellKlass = HEDoctorSignCell.class;
    siginModel.cellType = GDFiterCellTypeDoctorSign;
    siginModel.cellDisplayType = _privateDoctors.count > 0 && _type != HEDoctorInfoDetailsPageTypeByPrivateDoctor? GDCellDisplayShow: GDCellDisplayNone;
    
    // 医生服务
    GDFiterCellModel *serverModel = [GDFiterCellModel new];
    serverModel.cellKlass = HEDoctorServerCell.class;
    serverModel.cellType = GDFiterCellTypeDoctorServer;
    serverModel.cellDisplayType = self.formModel.doc_serverList.count > 0 ? GDCellDisplayShow: GDCellDisplayNone;
    
    // 医生服务详请
    GDFiterCellModel *serverInfoModel = [GDFiterCellModel new];
    serverInfoModel.cellKlass = HEDoctorServerInfoCell.class;
    serverInfoModel.cellType = GDFiterCellTypeDoctorServerDetails;
    serverInfoModel.cellDisplayType = _isShowServerDetailCell == YES ? GDCellDisplayShow: GDCellDisplayNone;

    // 评论头部
    GDFiterCellModel *commentHeadModel = [GDFiterCellModel new];
    commentHeadModel.cellKlass = HEDoctorCommentHeadCell.class;
    commentHeadModel.cellType = GDFiterCellTypeDoctorCommentHead;
    commentHeadModel.cellDisplayType = _type == HEDoctorInfoDetailsPageTypeByPrivateDoctor ? GDCellDisplayNone : GDCellDisplayShow ;

    // 评论
    GDFiterCellModel *commentModel = [GDFiterCellModel new];
    commentModel.cellKlass = HEDoctorCommentCell.class;
    commentModel.cellType = GDFiterCellTypeDoctorComment;
    commentModel.cellDisplayType = _commentList.count > 0 && _type != HEDoctorInfoDetailsPageTypeByPrivateDoctor ? GDCellDisplayShow: GDCellDisplayNone;
    
    // 服务说明
    GDFiterCellModel *noticeModel = [GDFiterCellModel new];
    noticeModel.cellKlass = HEDoctorServerNoticeCell.class;
    noticeModel.cellDisplayType = _type == HEDoctorInfoDetailsPageTypeByPrivateDoctor ? GDCellDisplayShow: GDCellDisplayNone;
    

    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[headModel, siginModel, serverModel, serverInfoModel, commentHeadModel, commentModel, noticeModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];

    for (GDFiterCellModel *model in classArr) {
         NSMutableArray *secs = [NSMutableArray array];
         
        // 隐藏未达到条件的cell
         if (model.cellDisplayType == GDCellDisplayNone) {
             continue;
         }
         else if (model.cellType == GDFiterCellTypeDoctorComment) {
             for (HEDoctorCommentModel *item in _commentList) {
                 [secs addObject:commentModel];
             }
         }
         else {
            [secs addObject:model];
        }
         
        [_sections addObject: secs];
     }
    
    [_tableView reloadData];
}

#pragma mark -

- (void)loadData {
    __weak typeof(self) weakself = self;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        weakself.group = dispatch_group_create();
        [weakself loadServerData];
        [weakself loadCommentData];
//        [weakself loadUserPrivateData];

        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(weakself.group, queue, ^{
            dispatch_main_async_safe(^{
   
                [weakself initCell];
            })
        });
    });
 
}

- (void)loadServerData {
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KdoctorServer parameters:@{@"user_id":_userId} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.details = [HEDoctorServerResponse mj_objectWithKeyValues:response.data];
        
        [self dealServerData];
        dispatch_group_leave(weakself.group);
    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(weakself.group);
    }];
}

- (void)dealServerData {
    
    _privateDoctors = @[].mutableCopy;
    _showList = @[].mutableCopy;
    
    for (HEDoctorInfoModel *item in self.details.service) {
        if (item.channel == HEChannelTypePrivateDoctors) {
            [_privateDoctors addObject:item];
        }else {
            
            if (item.channel == HEChannelTypeHealthGuide) {
                item.icon = @"doctor_indicator";
            }else if (item.channel == HEChannelTypePTConsultation) {
                item.icon = @"doctor_tw";
            }else {
                item.icon = @"doctor_plan";
            }
            [_showList addObject:item];
        }
    }
}

- (void)loadCommentData {
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;
    
    HEPageRequest *params = [HEPageRequest new];
    params.pageNum = 1;
    params.pageSize = 4;
    [params addParmas:_userId key:@"target_id"];
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KDoctorComments parameters:params success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEPageResponse *response = [HEPageResponse mj_objectWithKeyValues:responseObject];
        [self.commentList addObjectsFromArray:[HEDoctorCommentModel mj_objectArrayWithKeyValuesArray:response.data.list]];
        
        self.formModel.doc_totalCommet = response.data.total;
        
        dispatch_group_leave(weakself.group);
    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(weakself.group);
    }];
}


- (void)loadUserPrivateData {
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KprivateDocinfo parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success && response.data != nil) {
//            weakself.isHasPrivate = YES;
        }
        dispatch_group_leave(weakself.group);
    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(weakself.group);
    }];
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
 
    if (fiterModel.cellType == GDFiterCellTypeDoctorServer) {
        return 145;
    }
    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
               [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
     GDFiterCellModel *fiterModel = sec[indexPath.row];
    if (fiterModel.cellType == GDFiterCellTypeDoctorCommentHead) {
        HEDoctorCommentListViewController *vc = [HEDoctorCommentListViewController new];
        vc.userId = _userId;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark - UITableViewDelegate
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    NSMutableArray *sec = _sections[section];
//    GDFiterCellModel *fiterModel = sec.lastObject;
//    
//    if (fiterModel.cellType == GDFiterCellTypeDoctorCommentHead  ) {
//        return 10;
//    }
//    return CGFLOAT_MIN;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    UIView *v = [[UIView alloc] init];
//    v.backgroundColor = CViewBgColor;
//    return v;
//}


#pragma mark - HEDoctorServerCellDelegate
- (void)chooseDoctorServerType:(HEDoctorServerCell *)cell withModel:(HEDoctorInfoModel *)model {
    if (![DYTools isBlankString:model.detail_mobile_html]) {
        _isShowServerDetailCell = YES;
    }else {
        _isShowServerDetailCell = NO;
    }
    self.formModel.doc_selectServer = model;
    [self initCell];
    [self changeTabbarView];
}

- (void)changeTabbarView {
    HEDoctorInfoModel *model = self.formModel.doc_selectServer;

    if (_type == HEDoctorInfoDetailsPageTypeByPrivateDoctor) {
        NSString *titleStr = [NSString stringWithFormat:@"去签约￥%@", [NSDecimalNumber rounding:model.price afterPoint:2], model.unit];
        [_bottomView setTitle:titleStr forState:UIControlStateNormal];
    }else {
        NSString *titleStr = [NSString stringWithFormat:@"%@￥%@/%@", model.server_name, [NSDecimalNumber rounding:model.price afterPoint:2], model.unit];
        [_bottomView setTitle:titleStr forState:UIControlStateNormal];
    }
}

#pragma mark - HEDoctorSignCellDelegate
- (void)toDoctorMainPage {
    HEDoctorMainPageViewController *vc = [HEDoctorMainPageViewController new];
    vc.userId = _userId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)toSignPage {
    HEDoctorInfoDetailsViewController *vc = [HEDoctorInfoDetailsViewController new];
    vc.userId = _userId;
    vc.type = HEDoctorInfoDetailsPageTypeByPrivateDoctor;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)changeCareStatus:(BOOL)isCollection {
    [self careReq:isCollection];
}

/// 关注
- (void)careReq:(BOOL)isCollection {
    
    NSMutableDictionary *params = @{}.mutableCopy;
    if (isCollection) {
        [params setValue:_userId forKey:@"collection_source_id"];
        [params setValue: _details.info.skilful forKey:@"collection_brief"];
        [params setValue:@"doctor" forKey:@"collection_type"];
        [params setValue:_details.info.realname forKey:@"collection_name"];
        [params setValue:@1 forKey:@"status"];
    }else {
        [params setValue:_userId forKey:@"collection_source_id"];
        [params setValue:@"doctor" forKey:@"collection_type"];
        [params setValue:@0 forKey:@"status"];
    }
 
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KsaveCollection parameters:params success:^(id  _Nonnull responseObject) {
        HEResponse *rep = [HEResponse mj_objectWithKeyValues:responseObject];
        if (rep.success) {
            if ([@"2" isEqualToString:self.details.info.user_doc_collection]) {
                self.details.info.user_doc_collection = nil;
            }else {
                self.details.info.user_doc_collection = @"2";
            }
        }
        [self.tableView reloadData];
//        [self loadData];
    } failure:^(NSError * _Nonnull error) {
    }];
}
 
-(void)toApplyPlusPage {
    HEApplyPlusViewController *vc = [HEApplyPlusViewController new];
    vc.userModel = _details.info;
    vc.selectServerModel = self.formModel.doc_selectServer;
    [self.navigationController pushViewController:vc animated:YES];
}

@end
